package com.youlai.system.controller;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.youlai.system.common.model.Option;
import com.youlai.system.common.result.PageResult;
import com.youlai.system.common.result.Result;
import com.youlai.system.model.entity.SysCourse;
import com.youlai.system.model.form.CourseForm;
import com.youlai.system.model.query.CoursePageQuery;
import com.youlai.system.model.vo.CoursePageVO;
import com.youlai.system.model.vo.CourseScoreCountVO;
import com.youlai.system.plugin.dupsubmit.annotation.PreventDuplicateSubmit;
import com.youlai.system.service.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 故障控制器
 */
@Tag(name = "09.故障接口")
@RestController
@RequestMapping("/api/v1/courses")
@RequiredArgsConstructor
public class SysCourseController {

    private final SysCourseService courseService;

    private final SysScoreService scoreService;

    private final DegreeDataExecService degreeDataExecService;

    private final SysFrequencyService frequencyService;

    @Operation(summary = "故障分页列表")
    @GetMapping("/page")
    public PageResult<CoursePageVO> getCoursePage(@ParameterObject CoursePageQuery queryParams) {
        IPage<CoursePageVO> result = courseService.getCoursePage(queryParams);
        Map<Long, CourseScoreCountVO> courseScoreCountVOMap = scoreService.getAllCourseScoreCountMap();
        result.getRecords().forEach(coursePageVO -> {
            CourseScoreCountVO courseScoreCountVO = courseScoreCountVOMap.get(coursePageVO.getId());
            if (courseScoreCountVO != null) {
                coursePageVO.setTotalCount(courseScoreCountVO.getTotalCount());
                coursePageVO.setSuccessCount(courseScoreCountVO.getSuccessCount());
                coursePageVO.setFailCount(courseScoreCountVO.getFailCount());
                coursePageVO.setSuccessRate(courseScoreCountVO.getSuccessRate());
            }
        });
        return PageResult.success(result);
    }

    @Operation(summary = "新增故障")
    @PostMapping
    @PreAuthorize("@ss.hasPerm('sys:course:add')")
    @PreventDuplicateSubmit
    public Result saveCourse(@RequestBody @Valid CourseForm courseForm) {
        boolean result = courseService.saveCourse(courseForm);
        return Result.judge(result);
    }

    @Operation(summary = "故障表单数据")
    @GetMapping("/{courseId}/form")
    public Result<CourseForm> getCourseForm(@Parameter(description = "故障ID") @PathVariable Long courseId) {
        CourseForm formData = courseService.getCourseForm(courseId);
        return Result.success(formData);
    }


    @Operation(summary = "修改故障")
    @PutMapping(value = "/{courseId}")
    @PreAuthorize("@ss.hasPerm('sys:course:edit')")
    public Result updateCourse(@Parameter(description = "故障ID") @PathVariable Long courseId, @RequestBody @Validated CourseForm courseForm) {
        SysCourse course = courseService.getById(courseId);
        boolean result = courseService.updateCourse(courseId, courseForm);
        if (course.getMonth() == null && courseForm.getMonth() != null) {
            degreeDataExecService.execResetExamPeriodDegreeScore(courseId);
        }

        if (course.getMonth() != null && courseForm.getMonth() != null && !course.getMonth().equals(courseForm.getMonth())) {
            degreeDataExecService.execResetExamPeriodDegreeScore(courseId);
        }

        return Result.judge(result);
    }

    @Operation(summary = "删除故障")
    @DeleteMapping("/{ids}")
    @PreAuthorize("@ss.hasPerm('sys:course:delete')")
    public Result deleteCourses(@Parameter(description = "故障ID，多个以英文逗号(,)分割") @PathVariable String ids) {
        Assert.isTrue(StrUtil.isNotBlank(ids), "故障科目删除数据为空");
        List<Long> idList = Arrays.stream(ids.split(",")).map(Long::parseLong).collect(Collectors.toList());
        boolean courseHasUsed = scoreService.courseHasUsed(idList);
        Assert.isTrue(!courseHasUsed, "故障科目使用中，不能被删除");
        boolean result = courseService.deleteCourses(idList);
        return Result.judge(result);
    }

    @Operation(summary = "故障科目下拉列表")
    @GetMapping("/options")
    public Result<List<Option>> listCourseOptions(@RequestParam(value = "gradeId", required = false) Long gradeId) {
        List<Option> list = courseService.listCourseOptions();
        if (gradeId != null) {
            List<Long> courseIdList = frequencyService.getCourseIdListByGradeId(gradeId);
            list.forEach(it -> {
                if (courseIdList.contains(Long.parseLong(it.getValue().toString()))) {
                    it.setLabel(it.getLabel() + "（√）");
                }
            });
        }
        return Result.success(list);
    }


}
